import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../api/api_service.dart';
import '../../models/user.dart';
import '../../providers/app_state.dart';
import '../../config/app_theme.dart';

enum FollowListType {
  followers,  // 粉丝列表
  following   // 关注列表
}

class FollowListScreen extends StatefulWidget {
  final String userId;
  final FollowListType type;
  final String username; // 用户名，用于显示标题

  FollowListScreen({
    required this.userId,
    required this.type,
    required this.username,
  });

  @override
  _FollowListScreenState createState() => _FollowListScreenState();
}

class _FollowListScreenState extends State<FollowListScreen> {
  final ApiService _apiService = ApiService();
  List<User> _users = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadUsers();
  }

  Future<void> _loadUsers() async {
    setState(() {
      _isLoading = true;
    });

    try {
      List<User> users = [];
      
      // 根据类型获取用户列表
      if (widget.type == FollowListType.followers) {
        users = await _apiService.getUserFollowers(widget.userId);
      } else {
        users = await _apiService.getUserFollowing(widget.userId);
      }

      setState(() {
        _users = users;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading users: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final title = widget.type == FollowListType.followers 
        ? '${widget.username}的粉丝' 
        : '${widget.username}的关注';
    
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : _users.isEmpty
              ? _buildEmptyView()
              : _buildUserList(),
    );
  }

  Widget _buildEmptyView() {
    final message = widget.type == FollowListType.followers
        ? '暂无粉丝'
        : '暂无关注的用户';
    
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            widget.type == FollowListType.followers
                ? Icons.people_outline
                : Icons.person_add_disabled,
            size: 64,
            color: Colors.grey[400],
          ),
          SizedBox(height: 16),
          Text(
            message,
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8),
          Text(
            widget.type == FollowListType.followers
                ? '活跃于社区，增加更多粉丝'
                : '关注有趣的用户，丰富你的内容',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserList() {
    return RefreshIndicator(
      onRefresh: _loadUsers,
      child: ListView.builder(
        itemCount: _users.length,
        itemBuilder: (context, index) {
          final user = _users[index];
          return _buildUserItem(user);
        },
      ),
    );
  }

  Widget _buildUserItem(User user) {
    final appState = Provider.of<AppState>(context);
    final isCurrentUser = appState.currentUser?.id == user.id;
    final isFollowing = appState.isFollowing(user.id);
    
    return ListTile(
      leading: CircleAvatar(
        backgroundImage: NetworkImage(user.avatar),
      ),
      title: Text(
        user.username,
        style: TextStyle(
          fontWeight: FontWeight.bold,
        ),
      ),
      subtitle: user.bio != null && user.bio!.isNotEmpty
          ? Text(
              user.bio!,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            )
          : null,
      trailing: isCurrentUser
          ? null
          : TextButton(
              onPressed: () {
                appState.toggleFollowUser(user.id);
              },
              style: TextButton.styleFrom(
                backgroundColor: isFollowing ? Colors.grey[200] : AppTheme.primaryColor,
                primary: isFollowing ? Colors.black87 : Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.0),
                ),
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                minimumSize: Size(80, 32),
              ),
              child: Text(isFollowing ? '已关注' : '关注'),
            ),
      onTap: () {
        // 导航到用户资料页
        // TODO: 实现用户资料页
      },
    );
  }
} 